package org.example.heap;


import com.sun.xml.internal.ws.org.objectweb.asm.ClassWriter;
import org.springframework.asm.Opcodes;

/**
 * 在JDK 7之前使用的是永久代
 * -XX:PermSize=10m -XX:MaxPermSize=10m
 *
 * 测试元空间异常
 * -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
 * 方法区中存放的是类的数据结构，只要不断往方法区中加入新的类，就会产生方法区的溢出，可以使用类加载器不断加载类或者动态代理不断生成类来演示。
 * @author youshang
 * @date 2022/03/24 09:15
 **/
public class MetaspaceOOMTest extends ClassLoader {
    public static void main(String[] args) {
        int j = 0;
        try {
            MetaspaceOOMTest metaspaceOOMTest = new MetaspaceOOMTest();

            for (int i = 0; i < 100000; i++) {
                ClassWriter classWriter = new ClassWriter(0);
                classWriter.visit(Opcodes.V1_8,Opcodes.ACC_PUBLIC,"Class"+i,null,"java/lang/Object",null);
                byte[] code = classWriter.toByteArray();
                metaspaceOOMTest.defineClass("Class"+i,code,0,code.length);
                j++;
            }
        }finally {
            System.out.println(j);
        }
    }
}
